#include <QDate>
#include <QDateEdit>
#include <QDebug>

#include "datedelegate.h"
#include "logger.h"
#include "defs.h"
#include "manager.h"

DateDelegate::DateDelegate(QObject *parent) :
    QStyledItemDelegate (parent)
{
}

QString DateDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
    if (!value.toDate().isValid())
    {
        return QStyledItemDelegate::displayText(NOT_CORRECT, locale);
    }
    QDate dt = value.toDate();
    return dt.toString(DateFormat);
}

QWidget *DateDelegate::createEditor(QWidget *parent,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &) const
{
    QDateEdit *dateEdit = new QDateEdit(parent);
    dateEdit->setGeometry(option.rect);
    dateEdit->setDisplayFormat(DateFormat);
    return dateEdit;
}

void DateDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QDateEdit *edt = qobject_cast<QDateEdit*>(editor);
    QDate dt ( index.data().toDate() );
    edt->setDate(dt);
}

void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                const QModelIndex &index) const
{
    QDateEdit *dateEdit = qobject_cast<QDateEdit*>(editor);
    QDate gotDate ( dateEdit->date() );
    QString ageInString = doubleToQString(App->pacient()->ageAtDate(gotDate));
    // WARN: IC_Age == OC_Age
    model->setData( model->index(index.row(), IC_Age), ageInString);
    model->setData( index, gotDate);
}

QSize DateDelegate::sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const
{
    return QSize(110,30);
}
